package 笔试;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

public class 去哪儿_滑动窗口的最大值 {
    public int[] maxSlidingWindow (int[] nums, int k) {
        // write code here
        int ll = nums.length - k + 1;
        if(ll < 1) {
            return new int[0];
        }
        int[] res = new int[ll];
        if(nums == null || nums.length == 0) {
            return res;
        }
        int tmpP = ll;
        int m = 0;
        int p = 0;
        int l = 0;
        int r = k-1;
        while(tmpP > 0) {
            if(tmpP == ll) {
                int tmp = nums[l];
                for (int i = l+1; i <= r; i++) {
                    if(nums[i] > tmp) {
                        tmp = nums[i];
                        p = i;
                    }
                }
                res[m++] = nums[tmp];
                tmpP--;
                l++;
                r++;
            } else {
                if(p == l-1) {
                    int tmp = nums[l];
                    for (int i = l+1; i <= r; i++) {
                        if(nums[i] > tmp) {
                            tmp = nums[i];
                            p = i;
                        }
                    }
                    res[m++] = nums[tmp];
                    tmpP--;
                    l++;
                    r++;
                } else {
                    int tmp = nums[p];
                    for (int i = p+1; i <= r; i++) {
                        if(nums[i] > tmp) {
                            tmp = nums[i];
                            p = i;
                        }
                    }
                    res[m++] = nums[tmp];
                    tmpP--;
                    l++;
                    r++;
                }
            }
        }
        return res;
    }

    public int[] maxSlidingWindow1 (int[] nums, int k) {
        // write code here
        int n = nums.length;
        PriorityQueue<int[]> pq = new PriorityQueue<int[]>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] != o2[0] ? o2[0] - o1[0] : o2[1] - o1[1];
            }
        });
        for (int i = 0; i < k; i++) {
            pq.offer(new int[]{nums[i], i});
        }
        int[] res = new int[n-k+1];
        res[0] = pq.peek()[0];
        for (int i = k; i < n; i++) {
            pq.offer(new int[]{nums[i], i});
            while (pq.peek()[1] <= i-k) {
                pq.poll();
            }
            res[i-k+1] = pq.peek()[0];
        }
        return res;
    }
}
